<template>
    <el-button type="primary" style="margin-bottom: 18px;" @click="addForeignKey">添加外键</el-button>
    <el-table :data="tableData" border>
        <el-table-column prop="name" label="名" />
        <el-table-column prop="field" label="字段" />
        <!-- <el-table-column prop="pattern" label="被引用的模式" /> -->
        <el-table-column prop="fatherTable" label="被引用的表（父）" />
        <el-table-column prop="fieldsReferenced" label="被引用的字段">
             <template #default="{ row }">
                {{ getfieldsReferenced(row) }}
             </template>
            </el-table-column>
        <!-- <el-table-column prop="whenDeleting" label="删除时" />
        <el-table-column prop="whenUpdating" label="更新时" /> -->
        <el-table-column label="操作">
            <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleEditClick(row.id)">编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDeleteClick(row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog v-model="innerVisible" width="30%" :title="form.id ? '修改外键' : ' 添加外键'" append-to-body :close-on-click-modal="false">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
            <el-form-item label="名" prop="name">
                <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="字段" prop="field">
                <el-select v-model="form.field" placeholder="请选择字段">
                    <el-option v-for="(item, index) in fieldTableData" :key="index" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="被引用的模式" prop="pattern">
                <el-select v-model="form.pattern" placeholder="请选择被引用的模式" allow-create default-first-option filterable>
                    <el-option v-for="(item, index) in patternList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="被引用的表（父）" prop="fatherTable">
                <el-select v-model="form.fatherTable" placeholder="请选择被引用的表（父）" allow-create default-first-option>
                    <el-option v-for="(item, index) in fatherTableList" :key="index" :label="item.label" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="被引用的字段" prop="fieldsReferenced">
                <el-select v-model="form.fieldsReferenced" placeholder="请选择被被引用的字段" allow-create default-first-option>
                    <el-option v-for="(item, index) in fieldsReferencedList" :key="index" :label="item.name"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="删除时" prop="whenDeleting">
                <el-select v-model="form.whenDeleting" placeholder="请选择删除时" allow-create default-first-option>
                    <el-option label="CASCADE" value="CASCADE" />
                    <el-option label="ACTION" value="ACTION" />
                    <el-option label="RESTRICT" value="RESTRICT" />
                    <el-option label="SETNULL" value="SETNULL" />
                </el-select>
            </el-form-item><el-form-item label="更新时" prop="whenUpdating">
                <el-select v-model="form.whenUpdating" placeholder="请选择更新时" allow-create default-first-option>
                    <el-option label="CASCADE" value="CASCADE" />
                    <el-option label="NOACTION" value="NOACTION" />
                    <el-option label="RESTRICT" value="RESTRICT" />
                    <el-option label="SETNULL" value="SETNULL" />
                </el-select>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <el-button @click="cancel(formRef)">取消</el-button>
            <el-button type="primary" @click="saveForeignKey(formRef)">保存</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox, ElMessage } from "element-plus"
import { ref, computed } from "vue"
import { useForeignKey } from '@/store/foreignKey.ts';
import { storeToRefs } from "pinia"
const useForeignKeyStore = useForeignKey()
import { useField } from '@/store/field.ts';
import { useApp } from '@/store/app.ts';
const useFieldStore = useField()
const useAppStore = useApp()
const { tableData: fieldTableData } = storeToRefs(useFieldStore)
const { tableData } = storeToRefs(useForeignKeyStore)
const { treeData } = storeToRefs(useAppStore)
const formRef = ref<FormInstance>()

interface RuleForm {
    id?: number | string
    name: string,
    field: string,
    pattern: string,
    fatherTable: string,
    fieldsReferenced: string,
    whenDeleting: string,
    whenUpdating: string,
}
const innerVisible = ref(false)
const form = ref<RuleForm>({
    name: '',
    field: '',
    pattern: 'Default',
    fatherTable: '',
    fieldsReferenced: '',
    whenDeleting: '',
    whenUpdating: ''
})
const patternList = ref(
    [{
        value: 'Default',
        label: 'Default',
    },]
)
const fatherTableList = computed(() => {
    if (treeData.value[0].children && treeData.value[0].children.length > 0) {
        return treeData.value[0].children
    } else {
        return []
    }
})
const fieldsReferencedList = computed(() => {
    if (form.value.fatherTable == '') return []
    else {
        if (treeData.value[0].children && treeData.value[0].children.length > 0) {
            const reslut = treeData.value[0].children.filter((it: any) => it.id == form.value.fatherTable)
            return reslut[0] ? reslut[0].otherData.data.columns : []
        } else {
            return []
        }
    }
})
const getfieldsReferenced =computed(()=>(row)=> fatherTableList.value.find((its:any)=> its.id==row.fatherTable).otherData.data.columns.find(its=> its.id==row.fieldsReferenced).name)
const rules = {
    name: [
        { required: true, message: '请输入名', trigger: 'blur' },
        { min: 1, max: 50, message: '长度1-50字符', trigger: 'blur' },
    ],
    field: [{
        required: true,
        message: '请选择字段',
        trigger: 'change',
    }],
    pattern: [{
        required: true,
        message: '请选择被引用的模式', trigger: 'change',
    }],
    fatherTable: [{
        required: true,
        message: '请选择被引用的表（父）', trigger: 'change',
    }],
    fieldsReferenced: [{
        required: true,
        message: '请选择被被引用的字段', trigger: 'change',
    }],
    whenDeleting: [{
        required: true,
        message: '请选择删除时', trigger: 'change',

    }],
    whenUpdating: [{
        required: true,
        message: '请选择更新时', trigger: 'change',

    }]
}
// 删除
const handleDeleteClick = (id: number | string) => {
    ElMessageBox.confirm('确定要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        useForeignKeyStore.delete(id)
    }).catch(() => {
        ElMessage.info('你取消了删除')
    })
}
const addForeignKey = () => {
    innerVisible.value = true
}
const handleEditClick = (row: RuleForm) => {
    form.value = { ...row }
    innerVisible.value = true
}
// 取消
const cancel = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    innerVisible.value = false;
    form.value = {
        name: '',
        field: '',
        pattern: 'Default',
        fatherTable: '',
        fieldsReferenced: '',
        whenDeleting: '',
        whenUpdating: ''
    }
}
// 保存
const saveForeignKey = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            useForeignKeyStore.set(form.value)
            innerVisible.value = false;
            formEl.resetFields()
            form.value = {
                name: '',
                field: '',
                pattern: 'Default',
                fatherTable: '',
                fieldsReferenced: '',
                whenDeleting: '',
                whenUpdating: ''
            }
        } else {
            ElMessage.warning('添加失败')
        }
    })
}
</script>

<style lang="sass" scoped>

</style>